#include "commodity_list.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>



void COMMODITY_LIST_Init(commodity_list_p *ptr)
{
    *ptr = (commodity_list_t*)malloc(sizeof(commodity_list_t));
    if(*ptr == NULL)
    {
        printf("malloc error:");
        exit(1); // 使用exit(1)来终止程序
    }
    (*ptr)->commodity_num = NULL;
    (*ptr)->commodity = NULL;
    (*ptr)->next = NULL;
    (*ptr)->Location = -1;
}

int COMMODITY_LIST_Update(commodity_list_p ptr)
{
    FILE *fd = fopen("./Data/commodity/Price_list.txt", "r+");
    if(fd == NULL)
    {
        printf("open file error\n");
        return 0;
    }
    char buf[255];
    commodity_list_p p = ptr;
    while(1)
    {
        commodity_list_t *new_node = (commodity_list_t*)malloc(sizeof(commodity_list_t));
        if(new_node == NULL)
        {
            printf("malloc error:");
            return 0;
        }
        new_node->commodity = (commodity_t*)malloc(sizeof(commodity_t));
        if(new_node->commodity == NULL)
        {
            printf("malloc error:");
            free(new_node);
            return 0;
        }
        char *set = fgets(buf, 255, fd);
        if(set == NULL)
        {
            break;
        }
        char *p1 = strtok(buf, ",");
        int i = 0;
        while (p1 != NULL)
        {
            printf("%s\n", p1);
            if(i == 0)
                strcpy(new_node->commodity->commodity_name, p1);
            else if(i == 1)
                strcpy(new_node->commodity->commodity_id, p1);
            else if(i == 2)
                strcpy(new_node->commodity->commodity_price, p1);
            else if(i == 3)
                strcpy(new_node->commodity->commodity_type, p1);   
            i++;
            p1 = strtok(NULL, ",");

        }
        new_node->next = NULL;
        if(p->next == NULL)
        {
            p->next = new_node;
        }
        else
        {
            commodity_list_p temp = p->next;
            while(temp->next != NULL)
            {
                temp = temp->next;
            }
            temp->next = new_node;
        }
        p = p->next;
    }
    fclose(fd);
    return 0;
}

void COMMODITY_LIST_show_list(commodity_list_p ptr)
{
    commodity_list_t *p = ptr->next;
    while(p != NULL)
    {
        printf("name:%s id:%s price:%s type:%s\n", p->commodity->commodity_name, p->commodity->commodity_id, p->commodity->commodity_price, p->commodity->commodity_type);
        p = p->next;
        //sleep(1);
    }
}

void Lis_commty_tDestory(commodity_list_p *L)
{
	if (*L == NULL)
	{
		printf("List is NULL\r\n");
	    return ;
	}
		
	commodity_list_p delete = NULL;
	commodity_list_p p = *L;
	while (p != NULL)
	{
		delete = p;
		p = p->next;
		free(delete);
	}
	*L = NULL;
	printf("List Destory successfully\r\n");
}

